﻿

var RE = {};

RE.currentSelection;

RE.editor = document.getElementById('editor');

// Initializations
RE.callback = function () {
    //window.location.href = "re-callback://" + encodeURI(RE.getHtml());
}

RE.setHtml = function (contents) {
    RE.editor.innerHTML = decodeURIComponent(contents.replace(/\+/g, '%20'));

    //刷新样式
    setTimeout(function () {
        loadStyle();
    }, 100);

    //执行回调
    setTimeout(function () {
        RE.callback();
    }, 200);
}

//获取类容
RE.getHtml = function () {
    return RE.editor.innerHTML.replace(editorHead, "");
}

RE.getText = function () {
    return RE.editor.innerText;
}

RE.setFontSize = function (size) {
    RE.editor.style.fontSize = size;
}

RE.setBackgroundColor = function (color) {
    RE.editor.style.backgroundColor = color;
}

RE.setWidth = function (size) {
    RE.editor.style.minWidth = size;
}

RE.setHeight = function (size) {
    RE.editor.style.minHeight = size;
}

RE.setPlaceholder = function (placeholder) {
    RE.editor.setAttribute("placeholder", placeholder);
}

RE.undo = function () {
    document.execCommand('undo', false, null);
}

RE.redo = function () {
    document.execCommand('redo', false, null);
}

RE.setBold = function () {

    if (!$("#editor").is(":focus")) {
        setTimeout(function () {
            RE.setBold();
        }, 2000);
    }
    else {
        RE.restorerange();
        document.execCommand('bold', false, null);
    }
}

RE.setItalic = function () {
    document.execCommand('italic', false, null);
}

RE.setSubscript = function () {
    document.execCommand('subscript', false, null);
}

RE.setSuperscript = function () {
    document.execCommand('superscript', false, null);
}

RE.setStrikeThrough = function () {
    document.execCommand('strikeThrough', false, null);
}

RE.setUnderline = function () {
    document.execCommand('underline', false, null);
}

RE.setTextColor = function (color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('foreColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setTextBackgroundColor = function (color) {
    RE.restorerange();
    document.execCommand("styleWithCSS", null, true);
    document.execCommand('hiliteColor', false, color);
    document.execCommand("styleWithCSS", null, false);
}

RE.setHeading = function (heading) {
    document.execCommand('formatBlock', false, '<h' + heading + '>');
}

RE.setIndent = function () {
    document.execCommand('indent', false, null);
}

RE.setOutdent = function () {
    document.execCommand('outdent', false, null);
}

RE.setJustifyLeft = function () {
    document.execCommand('justifyLeft', false, null);
}

RE.setJustifyCenter = function () {
    document.execCommand('justifyCenter', false, null);
}

RE.setJustifyRight = function () {
    document.execCommand('justifyRight', false, null);
}

RE.setBlockquote = function () {
    document.execCommand('formatBlock', false, '<blockquote>');
}

//插入图片
RE.insertImage = function (url) {
    var html = '<img style = "width:100%;height:auto;" src="' + url + '" /><div><br /></div><div><br /></div>';
    RE.insertHTML(html);
}

//插入音频
RE.insertSound = function (url) {
    var html = '<audio src="' + url + '" controls="controls"></audio><br><br><br>';
    RE.insertHTML(html);
}

//插入视频
RE.insertVideo = function (tag) {
    tag = decodeURIComponent(tag.replace(/\+/g, '%20'));
    RE.insertHTML(tag);

    //刷新样式
    setTimeout(function () {
        loadStyle();
    }, 100);
}

//插入一个换行
//RE.insertEmpty()
//{
//    RE.insertHTML("<div><br></div>");
//}

//插入html
RE.insertHTML = function (html) {

    if (!$("#editor").is(":focus")) {
        setTimeout(function () {
            RE.insertHTML(html);
        }, 2000);
    }
    else {
        RE.restorerange();
        document.execCommand('insertHTML', false, html);

        //让输入框失去焦点 隐藏IOS键盘
        $("#editor").blur();
    }
}

RE.insertLink = function (url, title) {
    RE.restorerange();
    var sel = document.getSelection();
    if (sel.toString().length != 0) {
        if (sel.rangeCount) {

            var el = document.createElement("a");
            el.setAttribute("href", url);
            el.setAttribute("title", title);

            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    RE.callback();
}

RE.prepareInsert = function () {

    document.getElementById("editor").focus();

    //    RE.backuprange();
}

RE.backuprange = function () {
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    RE.currentSelection = {
        "startContainer": range.startContainer,
        "startOffset": range.startOffset,
        "endContainer": range.endContainer,
        "endOffset": range.endOffset
    };
}

RE.restorerange = function () {
    var selection = window.getSelection();
    selection.removeAllRanges();
    var range = document.createRange();
    range.setStart(RE.currentSelection.startContainer, RE.currentSelection.startOffset);
    range.setEnd(RE.currentSelection.endContainer, RE.currentSelection.endOffset);
    selection.addRange(range);
}

RE.enabledEditingItems = function (e) {
    var items = [];
    if (document.queryCommandState('bold')) {
        items.push('bold');
    }
    if (document.queryCommandState('italic')) {
        items.push('italic');
    }
    if (document.queryCommandState('subscript')) {
        items.push('subscript');
    }
    if (document.queryCommandState('superscript')) {
        items.push('superscript');
    }
    if (document.queryCommandState('strikeThrough')) {
        items.push('strikeThrough');
    }
    if (document.queryCommandState('underline')) {
        items.push('underline');
    }
    if (document.queryCommandState('insertOrderedList')) {
        items.push('orderedList');
    }
    if (document.queryCommandState('insertUnorderedList')) {
        items.push('unorderedList');
    }
    if (document.queryCommandState('justifyCenter')) {
        items.push('justifyCenter');
    }
    if (document.queryCommandState('justifyFull')) {
        items.push('justifyFull');
    }
    if (document.queryCommandState('justifyLeft')) {
        items.push('justifyLeft');
    }
    if (document.queryCommandState('justifyRight')) {
        items.push('justifyRight');
    }
    if (document.queryCommandState('insertHorizontalRule')) {
        items.push('horizontalRule');
    }
    var formatBlock = document.queryCommandValue('formatBlock');
    if (formatBlock.length > 0) {
        items.push(formatBlock);
    }

    //    window.location.href = "re-state://" + encodeURI(items.join(','));
}

RE.focus = function () {
    var range = document.createRange();
    range.selectNodeContents(RE.editor);
    range.collapse(false);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    RE.editor.focus();
}

RE.blurFocus = function () {
    RE.editor.blur();
}

//添加图片点击事件
RE.addImgClick = function () {
    $("img").each(function (i) {
        var ck = $(this).attr("onclick");
        if (!ck) {
            $(this).attr("onclick", "delImg(this);");
        }
    });
}

// Event Listeners
//RE.editor.addEventListener("input", RE.callback);
//RE.editor.addEventListener("keyup", function (e) {
//    var KEY_LEFT = 37, KEY_RIGHT = 39;
//    if (e.which == KEY_LEFT || e.which == KEY_RIGHT) {
//        RE.enabledEditingItems(e);
//    }
//});
//RE.editor.addEventListener("click", RE.enabledEditingItems);


//编辑器头部
var editorHead = '<div id="replace_div" contenteditable="false" style="width: 100%; height: 0px; position: absolute;bottom: 0px; overflow: hidden;">防止IOS跳回顶部</div>';

//判断是否保存了当前的光标位置
var isSava = false;

$(function () {
    RE.prepareInsert();
    savaRange();
});
//保存Range
function savaRange() {
    if ($("#editor").is(":focus")) {
        RE.backuprange();
        if (!isSava) {
            $("#editor").prepend(editorHead);
        }
        isSava = true;
    }
    setTimeout("savaRange();", 200);
}

//删除img标签
function delImg(tag) {
    if (confirm("确定要删除该图片？")) {
        $(tag).remove();

        setTimeout(function () {
            RE.callback();
        }, 100);
    }
}


//初始化一些样式
function loadStyle() {

    //设置播放器尺寸
    if ($("iframe").length > 0) {
        var width = $("#wrap").width();
        var heigth = width * 360 / 640;
        $("iframe").attr("width", "100%");
        $("iframe").attr("height", heigth);
    }
}
